<template>
  <div>
<!--    面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    卡片式内容包裹-->
    <el-card>
<!--      搜索框-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
<!--      用户表格-->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <!--          使用slot-scope来接受这一行的值-->
          <template v-slot="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template v-slot="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeUserById(scope.row.id)"></el-button>
            <el-tooltip placement="top" content="分配角色" :enterable="false">
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
<!--      添加用户对话框-->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="30%" @close="addDialogClosed">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
<!--      修改用户对话框-->
      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="30%" @close="editDialogClosed">
        <el-form :model="editform" ref="editForm" :rules="editFormRules" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editform.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editform.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editform.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editDialogVisible = false" type="info">取消</el-button>
          <el-button @click="editUserInfo" type="primary">确定</el-button>
        </span>
      </el-dialog>
<!--      分配角色对话框-->
      <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%">
        <div>
          <p>当前用户: {{userInfo.username}}</p>
          <p>当前角色: {{userInfo.role_name}}</p>
          <p>分配新角色：<el-select v-model="selectRoleId" clearable placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
          </p>
        </div>
        <span slot="footer">
          <el-button @click="setRoleDialogVisible = false">取消</el-button>
          <el-button @click="saveRoleInfo" type="primary" >确认</el-button>
        </span>
      </el-dialog>
<!--      分页器-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data () {
    // 邮箱验证规则
    var checkEmail = (rule, value, cb) => {
      // 正则匹配邮箱
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 手机号验证规则
    var checkMobile = (rule, value, cb) => {
      // 正则匹配邮箱
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 获取用户列表参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 用来保存要修改的用户数据
      editform: {},
      // 添加用户的表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度应在3~10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '用户名长度应在6~15个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改用户数据的验证规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制分配角色对话框
      setRoleDialogVisible: false,
      // 用来保存当前用户信息
      userInfo: {},
      // 所有的角色列表
      roleList: [],
      // 当前选择的角色id
      selectRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: result } = await this.$http.get('users', { params: this.queryInfo })
      console.log(result)
      if (result.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userlist = result.data.users
      this.total = result.data.total
    },
    // 监听pagesize 事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听currentpage事件
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听状态改变事件
    async userStateChanged (userinfo) {
      const { data: result } = await this.$http.put('users/' + userinfo.id + '/state/' + userinfo.mg_state)
      if (result.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('修改失败')
      }
      this.$message.success({ message: '修改成功', showClose: true })
    },
    // 监听添加用户对话框关闭时间
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定按钮事件
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        // eslint-disable-next-line no-useless-return
        if (!valid) return
        // 发起新增用户请求
        const { data: result } = await this.$http.post('users', this.addForm)
        if (result.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 修改用户对话框
    async showEditDialog (id) {
      const { data: result } = await this.$http.get('users/' + id)
      console.log(result)
      if (result.meta.status !== 200) return this.$message.error('请求失败')
      this.editform = result.data
      this.editDialogVisible = true
    },
    // 监听修改对话框关闭事件
    editDialogClosed () {
      this.$refs.editForm.resetFields()
    },
    // 点击修改提交预验证
    editUserInfo () {
      // 获取表单验证结果
      this.$refs.editForm.validate(async valid => {
        // eslint-disable-next-line no-useless-return
        if (!valid) return
        // 验证通过，发起修改请求
        const { data: result } = await this.$http.put('users/' + this.editform.id, {
          email: this.editform.email,
          mobile: this.editform.mobile
        })
        if (result.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.getUserList()
        this.editDialogVisible = false
        this.$message.success('修改成功')
      })
    },
    // 点击删除弹框
    async removeUserById (id) {
      const confirmResult = await this.$confirm('是否永久删除该用户', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消')
      }
      const { data: result } = await this.$http.delete('users/' + id)
      if (result.meta.status !== 200) return this.$message.error('删除失败')
      this.queryInfo.pagenum = 1 // 将页数跳转到第一页
      this.getUserList()
      this.$message.success('删除成功')
    },
    // 分配角色
    async setRole (userInfo) {
      // 获取信息
      this.userInfo = userInfo
      // 获取所有角色列表
      const { data: result } = await this.$http.get('roles')
      if (result.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleList = result.data
      console.log(this.roleList)
      // 显示对话框
      this.setRoleDialogVisible = true
    },
    // 发送分配角色请求
    async saveRoleInfo () {
      if (!this.selectRoleId) {
        return this.$message.error('请选择需要分配的角色')
      }
      const { data: result } = await this.$http.put('users/' + this.userInfo.id + '/role', {
        rid: this.selectRoleId
      })
      if (result.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success('分配角色成功')
      this.selectRoleId = ''
      this.getUserList()
      this.setRoleDialogVisible = false
    }
  }
}
</script>

<style scoped>

</style>
